package com.kf.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
	
	@RequestMapping("/hello")
	@ResponseBody
	public String hello(){
		
		return "ok";
	}
	@RequestMapping("/testT")
	public String test(Model model){
		model.addAttribute("name", "testName");
		return "test";
	}
	
	@RequestMapping("/add")
	public String add(){
		return "user/add";
	}
	
	@RequestMapping("/update")
	public String update(){
		return "user/update";
	}
	
	@RequestMapping("/toLogin")
	public String toLogin(){
		return "login";
	}
	
	@RequestMapping("/noAuth")
	public String noAuth(){
		return "noAuth";
	}
	
	@RequestMapping("/login")
	public String login(String name, String pwd, Model model){
		//使用shiro编写认证操作
		//获取subject
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(name,pwd);
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			model.addAttribute("result", "用户名或密码不存在");
			e.printStackTrace();
			return "login";
		}catch (IncorrectCredentialsException e){
			model.addAttribute("result", "用户名或密码不存在"); 
			e.printStackTrace();
			return "login";
		}catch (AuthenticationException e){
			model.addAttribute("result", "用户名或密码不存在");
			e.printStackTrace();
			return "login";
		}
		return "redirect:/testT";
	}

}
